﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.Unity;
using System.Web;

namespace Lilium.Unity.LifetimeManagers
{
    public class PerRequestLifetimeManager : LifetimeManager
    {
        public override object GetValue()
        {
            return HttpContext.Current.Items[Key];
        }

        public override void RemoveValue()
        {
            var items = HttpContext.Current.Items;
            var item = items[Key] as IDisposable;
            items.Remove(Key);
            if (item != null)
                item.Dispose();
        }

        public override void SetValue(object newValue)
        {
            var items = HttpContext.Current.Items;
            var item = items[Key] as IDisposable;
            items[Key] = newValue;
            if (item != null)
                item.Dispose();
        }

        private readonly Guid Key = Guid.NewGuid();
    }
}